package org.uc3m.pfc.http;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

/**
 * 
 * @author esteban
 *
 */
public final class HttpHelper {

	// Class fields *******************************************************
	
	/** Buffer size. */
	private static final int BUFFER_SIZE = 1024;
	
	/** Static instance. */
	private static HttpHelper helper;
	
	
    // Constructor *******************************************************
	
	/**
	 * Default constructor.
	 */
	private HttpHelper() {
	}

	/**
	 * Get the helper.
	 * 
	 * @return static helper
	 */
	public static HttpHelper getHelper() {
		
		if (helper == null) {
			helper = new HttpHelper();
		}
		
		return helper;
	}

	
    // Public methods ****************************************************
	
	/**
	 * Executes a get HTTP request.
	 * 
	 * @param url of server
	 * @return content of response
	 */
	public String getContentFromUrl(final String url) {
		
		String content = null;

		try {
			InputStream in = getInputStreamFromUrl(url);
			
			if (in != null) {
				
				content = inputStreamToString(in);
			}
		} catch (Exception e) {
			
			// TODO handle error
			Log.e("[GET REQUEST]", "Network exception", e);
		}

		return content;
	}
	
	
    // Private methods ****************************************************
	
	/**
	 * Get the input stream from the url with a get request.
	 * 
	 * @param url server url
	 * @return input stream of request
	 * @throws Exception in case of error
	 */
	private InputStream getInputStreamFromUrl(final String url)
			throws Exception {

		InputStream content = null;
		HttpClient httpclient = new DefaultHttpClient();
		
		HttpResponse response = httpclient.execute(new HttpGet(url));
		content = response.getEntity().getContent();
		
		return content;
	}

	/**
	 * Get the string from the input stream.
	 * 
	 * @param content input stream
	 * @return string data
	 * @throws Exception in case of error
	 */
	private String inputStreamToString(final InputStream content) 
			throws Exception {

		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		byte[] buf = new byte[BUFFER_SIZE];
		int len = 0;
		
		while ((len = content.read(buf)) > 0) {
			bout.write(buf, 0, len);
		}
		
		content.close();
		
		return bout.toString();
	}
	
}

